/*
 * Title: 集合计算机栈（The SetStack Computer）
 * Author: Yuanshun L
 * Created : 09-otc-2021
 */

#include<iostream>
#include<vector>
#include<stack>
#include<map>
#include<set>
#include<string>
#include<cstdio>
using namespace std;

typedef set<int> Set;
map<Set,int> Map; // 将Set映射成ID
vector<Set> s; // 保存ID与Set的对应关系

stack<int> stk;

// 将空栈入栈
void push(){
    if(s.size()==0){
        s.push_back(Set());
        Map[Set()] = 0;
    }
    stk.push(0);
}

// 复制栈顶元素一份再将其入栈
void dup(){
    if(!stk.empty())
        stk.push(stk.top());
}


// 求并集
Set exec_union(int id1, int id2){
    Set s1 = s[id1];
    Set s2 = s[id2];
    Set s3;
    for(Set::iterator it=s1.begin();it!=s1.end();it++){
        s3.insert(*it);
    }
    for(Set::iterator it=s2.begin();it!=s2.end();it++){
        s3.insert(*it);
    }
    return s3;
}

// 求交集
Set exec_intersect(int id1, int id2){
    Set s1 = s[id1];
    Set s2 = s[id2];
    Set s3;
    for(Set::iterator it=s1.begin();it!=s1.end();it++){
        if(s3.count(*it)){
            s3.insert(*it);
        }
    }
    return s3;
}

int find_or_create_id(const Set st){
    int index;
    // 如果能找到
    if(Map.count(st)){
        return Map[st];
    }
    // 如果找不到则新建
    index = s.size();
    Map[st] = index;
    s.push_back(st);
    return index;
}

// 输出集合表示
void print_set_form(int id){
    int first=0;
    cout<<"{";
    if(!s[id].empty()){
        for(Set::iterator it=s[id].begin();it!=s[id].end();it++){
            if(first) cout<<",";
            else first=1;
            print_set_form(*it);
        }
    }
    cout<<"}";
}

int main() {
    freopen("data.in","r",stdin);
    freopen("data.out","w",stdout);

    int n; // 操作次数
    string cmd;
    cin >> n;


    while(n--){
        cin >> cmd;
        if(cmd[0]=='P') push();
        else if(cmd[0]=='D') dup();
        else{
            int s1 = stk.top(); stk.pop();
            int s2 = stk.top(); stk.pop();
            int id;
            Set x;
            if(cmd[0] == 'U')
                id = find_or_create_id(exec_union(s1,s2));

            if(cmd[0] == 'I')
                id = find_or_create_id(exec_intersect(s1,s2));

            if(cmd[0] == 'A'){
                x = s[s2]; x.insert(s1);
                id = find_or_create_id(x);
            }
            stk.push(id);
        }
        cout << s[stk.top()].size() << "-->";
        print_set_form(stk.top());
        cout<<endl;
    }


    return 0;
}